<template>
  <div>
    <section class="todoapp">
      <TodoAdd @add="onAdd" />

      <TodoList :items="displayTodos" @delete="onDelete" @update="onUpdate" />

      <TodoFooter :items="todos" :status.sync="status" />
    </section>
  </div>
</template>

<script>
import TodoAdd from "./components/TodoAdd.vue";
import TodoList from "./components/TodoList.vue";
import TodoFooter from "./components/TodoFooter.vue";
import request from "@/utils/request";
export default {
  components: {
    TodoAdd,
    TodoList,
    TodoFooter,
  },

  data() {
    return {
      todos: [
        // { id: 1, text: "吃饭", isDone: false },
        // { id: 2, text: "睡觉", isDone: true },
      ],
      status: "all", // 当前展示状态
    };
  },

  computed: {
    displayTodos() {
      switch (this.status) {
        case "active":
          return this.todos.filter((item) => !item.isDone);
        case "completed":
          return this.todos.filter((item) => item.isDone);
        default:
          return this.todos;
      }
    },
  },

  methods: {
    // 请求数据的方法
    async fetchData() {
      const resp = await request.get("/todos");
      console.log(resp);
      this.todos = resp;
    },

    // 删除
    async onDelete(id) {
      console.log("id", id);
      await request.delete("/todos/" + id);
      // 方案一: 手动修改数据
      this.todos = this.todos.filter((item) => item.id !== id);
      // 方案二: 再次调用 this.fetchData()
      // this.fetchData()
    },

    // 添加
    async onAdd(text) {
      const resp = await request.post("/todos", {
        text: text,
        isDone: false,
      });
      console.log("添加的数据", resp);
      this.todos.push(resp);
    },

    // 修改
    //    将 obj 中id排除掉, 剩余的内容单独组成一个对象
    async onUpdate({ id, ...payload }) {
      console.log(id, payload);
      const resp = await request.patch("/todos/" + id, payload);
      console.log("修改完成", resp);
      // 方案1.1
      // Object.assign(this.todos.find((item) => item.id === id), payload)
      // 方案1.2
      this.todos = this.todos.map((item) => {
        if (item.id === id) {
          return {
            ...item,
            ...payload,
          };
        } else {
          return item;
        }
      });
    },

    handleChange(status) {
      console.log("status", status);
      this.status = status;
    },
  },

  provide() {
    return {
      onDelete: this.onDelete,
      onUpdate: this.onUpdate
    }
  },

  mounted() {
    // 默认调用一次数据
    this.fetchData();
  },
};
</script>
